/***** Start Plugins code ****/	

/** Start Auto Suggest plugin **/

/**
*  Ajax Autocomplete for jQuery, version 1.1.5
*  (c) 2010 Tomas Kirda, Vytautas Pranskunas
*
*  Ajax Autocomplete for jQuery is freely distributable under the terms of an MIT-style license.
*  For details, see the web site: http://www.devbridge.com/projects/autocomplete/jquery/
*
*  Last Review: 07/24/2012
*/

/*jslint onevar: true, evil: true, nomen: true, eqeqeq: true, bitwise: true, regexp: true, newcap: true, immed: true */
/*global window: true, document: true, clearInterval: true, setInterval: true, jQuery: true */

(function ($) {
	var maxLength = 10;
	var reEscape = new RegExp('(\\' + ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'].join('|\\') + ')', 'g');

	function fnFormatResult(value, data, currentValue) {
		var pattern = '(' + currentValue.replace(reEscape, '\\$1') + ')';
	//	 alert ('Patern='+pattern+' : val='+value+' : data='+data+' : current='+currentValue);
		return value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>');
		
	}

	function Autocomplete(el, options) {
		this.el = $(el);
		this.el.attr('autocomplete', 'off');
		this.suggestions = [];
		this.data = [];
		this.badQueries = [];
		this.selectedIndex = -1;
		this.currentValue = this.el.val();
		this.intervalId = 0;
		this.cachedResponse = [];
		this.onChangeInterval = null;
		this.onChange = null;
		this.ignoreValueChange = false;
		this.serviceUrl = options.serviceUrl;
		this.isLocal = false;
		this.options = {
			autoSubmit: false,
			minChars: 1,
			maxHeight: 308,
			deferRequestBy: 0,
			width: 0,
			highlight: true,
			params: {},
			fnFormatResult: fnFormatResult,
			delimiter: null,
			zIndex: 9999
		};
		this.initialize();
		this.setOptions(options);
		this.el.data('autocomplete', this);
	}

	$.fn.autocomplete = function (options, optionName) {

		var autocompleteControl;

		if (typeof options == 'string') {
			autocompleteControl = this.data('autocomplete');
			if (typeof autocompleteControl[options] == 'function') {
				autocompleteControl[options](optionName);
			}
		} else {
			autocompleteControl = new Autocomplete(this.get(0) || $('<input />'), options);
		}
		return autocompleteControl;
	};


	Autocomplete.prototype = {

		killerFn: null,

		initialize: function () {

			var me, uid, autocompleteElId;
			me = this;
			uid = Math.floor(Math.random() * 0x100000).toString(16);
			autocompleteElId = 'Autocomplete_' + uid;

			this.killerFn = function (e) {
				if ($(e.target).parents('.autocomplete').size() === 0) {
					me.killSuggestions();
					me.disableKillerFn();
				}
			};

			if (!this.options.width) { this.options.width = this.el.width(); }
			this.mainContainerId = 'AutocompleteContainter_' + uid;

			$('<div id="' + this.mainContainerId + '" style="position:absolute;z-index:100000 !important;"><div class="autocomplete-w1"><div class="autocomplete" id="' + autocompleteElId + '" style="display:none; width:300px;"></div></div></div>').appendTo('body');

			this.container = $('#' + autocompleteElId);
			
			this.fixPosition();
			if (window.opera) {
				this.el.keypress(function (e) { me.onKeyPress(e); });
			} else {
				this.el.keydown(function (e) { me.onKeyPress(e); });
			}
			this.el.keyup(function (e) { me.onKeyUp(e); });
			this.el.blur(function () { me.enableKillerFn(); });
			this.el.focus(function () { me.fixPosition(); });
			this.el.change(function () { me.onValueChanged(); });
		},

		extendOptions: function (options) {
			$.extend(this.options, options);
		},

		setOptions: function (options) {
			var o = this.options;
			this.extendOptions(options);
			if (o.lookup || o.isLocal) {
				this.isLocal = true;
				if ($.isArray(o.lookup)) { o.lookup = { suggestions: o.lookup, data: [] }; }
			}
			$('#' + this.mainContainerId).css({ zIndex: o.zIndex });
			this.container.css({ maxHeight: o.maxHeight + 'px', width: o.width });
		},

		clearCache: function () {
			this.cachedResponse = [];
			this.badQueries = [];
		},

		disable: function () {
			this.disabled = true;
		},

		enable: function () {
			this.disabled = false;
		},

		fixPosition: function () {
			var offset = this.el.offset();
			$('#' + this.mainContainerId).css({ top: (offset.top + this.el.innerHeight()) + 'px', left: offset.left + 'px' });
		},

		enableKillerFn: function () {
			var me = this;
			$(document).bind('click', me.killerFn);
		},

		disableKillerFn: function () {
			var me = this;
			$(document).unbind('click', me.killerFn);
		},

		killSuggestions: function () {
			var me = this;
			this.stopKillSuggestions();
			this.intervalId = window.setInterval(function () { me.hide(); me.stopKillSuggestions(); }, 300);
		},

		stopKillSuggestions: function () {
			window.clearInterval(this.intervalId);
		},

		onValueChanged: function () {
			this.change(this.selectedIndex);
		},

		onKeyPress: function (e) {
			if (this.disabled || !this.enabled) { return; }
			// return will exit the function
			// and event will not be prevented
			switch (e.keyCode) {
				case 27: //KEY_ESC:
					this.el.val(this.currentValue);
					this.hide();
					break;
				case 9: //KEY_TAB:
				case 13: //KEY_RETURN:
					if (this.selectedIndex === -1) {
						this.hide();
						return;
					}
					this.select(this.selectedIndex);
					if (e.keyCode === 9) { return; }
					break;
				case 38: //KEY_UP:
					this.moveUp();
					break;
				case 40: //KEY_DOWN:
					this.moveDown();
					break;
				default:
					return;
			}
			e.stopImmediatePropagation();
			e.preventDefault();
		},

		onKeyUp: function (e) {
			if (this.disabled) { return; }
			switch (e.keyCode) {
				case 38: //KEY_UP:
				case 40: //KEY_DOWN:
					return;
			}
			clearInterval(this.onChangeInterval);
			if (this.currentValue !== this.el.val()) {
				if (this.options.deferRequestBy > 0) {
					// Defer lookup in case when value changes very quickly:
					var me = this;
					this.onChangeInterval = setInterval(function () { me.onValueChange(); }, this.options.deferRequestBy);
				} else {
					this.onValueChange();
				}
			}
		},

		onValueChange: function () {
			clearInterval(this.onChangeInterval);
			this.currentValue = this.el.val();
			var q = this.getQuery(this.currentValue);
			this.selectedIndex = -1;
			if (this.ignoreValueChange) {
				this.ignoreValueChange = false;
				return;
			}
			if (q === '' || q.length < this.options.minChars) {
				this.hide();
			} else {
				this.getSuggestions(q);
			}
		},

		getQuery: function (val) {
			var d, arr;
			d = this.options.delimiter;
			if (!d) { return $.trim(val); }
			arr = val.split(d);
			return $.trim(arr[arr.length - 1]);
		},

		getSuggestionsLocal: function (q) {
			var ret, arr, len, val, i;
			arr = this.options.lookup;
			len = arr.suggestions.length;
			
			ret = { suggestions: [], data: [] };
			q = q.toLowerCase();
			for (i = 0; i < len; i++) {
				val = arr.suggestions[i];
				
				/******************************************************************************/
				
				if (val.toLowerCase().indexOf(q) === 0) { // This is to match the first characters
			//	if (val.toLowerCase().indexOf(q) != -1) { // This is to match anywhere in the string
				//	alert('Val='+val+' q='+q);
					ret.suggestions.push(val);
					ret.data.push(arr.data[i]);
				}
				
			}
			return ret;
		},

		getSuggestions: function (q) {

			var cr, me;
			cr = this.isLocal ? this.getSuggestionsLocal(q) : this.cachedResponse[q]; //dadeta this.options.isLocal ||
			if (cr && $.isArray(cr.suggestions)) {
				this.suggestions = cr.suggestions;
				this.data = cr.data;
				this.suggest();
			} else if (!this.isBadQuery(q)) {
				me = this;
				me.options.params.query = q;
				$.get(this.serviceUrl, me.options.params, function (txt) { me.processResponse(txt); }, 'text');
			}
		},

		isBadQuery: function (q) {
			var i = this.badQueries.length;
			while (i--) {
				if (q.indexOf(this.badQueries[i]) === 0) { return true; }
			}
			return false;
		},

		hide: function () {
			this.enabled = false;
			this.selectedIndex = -1;
			this.container.hide();
		},

		suggest: function () {

			if (this.suggestions.length === 0) {
				this.hide();
				return;
			}

			var me, len, div, f, v, i, s, mOver, mClick;
			me = this;
			len = this.suggestions.length;
		//	len = 12
			
			f = this.options.fnFormatResult;
			v = this.getQuery(this.currentValue);
			mOver = function (xi) { return function () { me.activate(xi); }; };
			mClick = function (xi) { return function () { me.select(xi); }; };
			this.container.hide().empty();
			
			for (i = 0; i < len; i++) { /**********************************/
				s = this.suggestions[i];
				div = $((me.selectedIndex === i ? '<div class="selected"' : '<div') + ' title="' + s + '">' + f(s, this.data[i], v) + '</div>');
				div.mouseover(mOver(i)); /*********/
				div.click(mClick(i));
				this.container.append(div); 
				if (i > maxLength) break; /**** Limit results *****/
			}
			
			this.enabled = true;
			this.container.prepend('<h4>Search suggestions:</h4>'); /**********************************/
			this.container.show();
		},

		processResponse: function (text) {
			var response;
			try {
				response = eval('(' + text + ')');
			} catch (err) { return; }
			if (!$.isArray(response.data)) { response.data = []; }
			if (!this.options.noCache) {
				this.cachedResponse[response.query] = response;
				if (response.suggestions.length === 0) { this.badQueries.push(response.query); }
			}
			if (response.query === this.getQuery(this.currentValue)) {
				this.suggestions = response.suggestions;
				this.data = response.data;
				this.suggest();
			}
		},

		activate: function (index) {
			var divs, activeItem;
			divs = this.container.children('div');
			// Clear previous selection:
			if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) {
				$(divs.get(this.selectedIndex)).removeClass();
			}
			this.selectedIndex = index;
			if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) {
				activeItem = divs.get(this.selectedIndex);
				$(activeItem).addClass('selected');
			}
			return activeItem;
		},

		deactivate: function (div, index) {
			div.className = '';
			if (this.selectedIndex === index) { this.selectedIndex = -1; }
		},

		select: function (i) {
			var selectedValue, f;
			selectedValue = this.suggestions[i];
			if (selectedValue) {
				this.el.val(selectedValue);
				if (this.options.autoSubmit) {
					f = this.el.parents('form');
					if (f.length > 0) { f.get(0).submit(); }
				}
				this.ignoreValueChange = true;
				this.hide();
				this.onSelect(i);
			}
		},

		change: function (i) {
			var selectedValue, fn, me;
			me = this;
			selectedValue = this.suggestions[i];
			if (selectedValue) {
				var s, d;
				s = me.suggestions[i];
				d = me.data[i];
				me.el.val(me.getValue(s));
			}
			else {
				s = '';
				d = -1;
			}

			fn = me.options.onChange;
			if ($.isFunction(fn)) { fn(s, d, me.el); }
		},

		moveUp: function () {
			if (this.selectedIndex === -1) { return; }
			if (this.selectedIndex === 0) {
				this.container.children().get(0).className = '';
				this.selectedIndex = -1;
				this.el.val(this.currentValue);
				return;
			}
			this.adjustScroll(this.selectedIndex - 1);
		},

		moveDown: function () {
			if (this.selectedIndex === (this.suggestions.length - 1)) { return; }
			else if (this.selectedIndex === (maxLength+1)) { return; } /********* Max terms *********/
			
			this.adjustScroll(this.selectedIndex + 1);
		},

		adjustScroll: function (i) {
			var activeItem, offsetTop, upperBound, lowerBound;
			activeItem = this.activate(i);
			offsetTop = activeItem.offsetTop;
			upperBound = this.container.scrollTop();
			lowerBound = upperBound + this.options.maxHeight - 25;
			if (offsetTop < upperBound) {
				this.container.scrollTop(offsetTop);
			} else if (offsetTop > lowerBound) {
				this.container.scrollTop(offsetTop - this.options.maxHeight + 25);
			}
			this.el.val(this.getValue(this.suggestions[i]));
		},

		onSelect: function (i) {
			var me, fn, s, d;
			me = this;
			fn = me.options.onSelect;
			s = me.suggestions[i];
			d = me.data[i];
			me.el.val(me.getValue(s));
			if ($.isFunction(fn)) { fn(s, d, me.el); }
		},

		getValue: function (value) {
			var del, currVal, arr, me;
			me = this;
			del = me.options.delimiter;
			if (!del) { return value; }
			currVal = me.currentValue;
			arr = currVal.split(del);
			if (arr.length === 1) { return value; }
			return currVal.substr(0, currVal.length - arr[arr.length - 1].length) + value;
		}

	};

} (jQuery));
/** End Autosuggest plugin **/	



/***** End Plugins code ****/	

var prntBox = false; // print box flag

var terms = ["305","2030","2013 fellowship","25 year award","a series documents","a101","a101-1997","a101-2007","a102","a103","a105","A105-2007","a107","a107-2007","a111","a121","a132","a133","a134","A141","a201","a201 general conditions 2007","a201-1997","a201-2007","a232","a305","a305-1986","a310","a312","a401","a401-2007","a701","ACSA/AIA Topaz Medallion","aia 107","aia a305 form","aia alliances","AIA Awards","aia best practices","aia construction contracts","aia construction documents","aia contract documents","aia contract forms","aia contracts on demand","aia document a101","aia document a101-2007","aia document a105","aia document a107","aia document a107-2007","aia document a201-2007","aia document a305","aia document g702","aia document g703","AIA fellows","AIA Firm Award","aia form g702","aia forms","aia forms download","aia free documents download","aia g702","AIA Gold Medal","aia guide to the igcc","AIA Honorary Fellows","AIA honorary members","AIA Institute Honor Award for Architecture","AIA Institute Honor Award for Interiors","aia national convention","aia online documents","aia podcasts","aia publications","aia rss feeds","aia software","aia standard contract","aia substantial completion form","AIA twenty-five year award","aiarchitect","alliances","american institute of architects forms","Architect registration exam","Architecture Firm Award","Architecture Honor Award","are","associate members","associates award","awards","B series documents","b101","b101-2007","b102","b104","b105","b108","b141","b143","b151","b201","b305","best practices","bim","bookstore","building information model","building information modeling","C series documents","c132","c401","career center","certificate of completion","certificate of substantial completion","ces","ces discovery","ces provider webinars","change order","change order form","change orders","chapters","Collaborative & Professional Achievement Award","Collaborative Achievement Award","Collaborative and Professional Achievement Award","college of fellows","college of fellows","commitee on the environment","communities by design","components","construction administration","construction management","construction manager","construction manager at risk","contract between owner and contractor","contract documents download","contract documents software","contract documents software download","contract forms","contract software","contracts download","contracts free","convention","copyright","cornerstone partners","cote","cote top ten","cxd","design build","design build contract","disaster response","documents on demand","download a107","download aia documents","download aia software","download free aia forms","Download Software","e202","Edward C. Kemper Award","energy modeling guide","exhibitor catalog","FAIA","fellows","fellowship reference letters","fellowship requirements","fellowship sponsors","fellowship submission deadline","find an architect","firm award","forms g702 and g703","free aia contract documents","free aia contract forms","free aia document a305","free aia documents","free aia forms","G series documents","g612","g701","g701-2001","G702","g703","G704","g706","G706A","G707","g732","general conditions","Gold Medal","grassroots","Hon. AIA","Hon. FAIA","honor awards","Honorary Fellowship","honorary members","honorary membership","hurricane sandy","idp","igcc","Institute Honor Award for Architecture","Institute Honor Award for Interiors","Institute Honor Award for Regional and Urban Design","integrated project delivery","Interior Architecture Honor Award","intern development program","international green construction code","ipd","join aia","Kemper Award","knowledge communities","knowledgenet","Library Awards","licensure","lien waiver","member groups","membership","mentors","mentorship","nac","national associates committee","newsletters","notice to proceed","owner and contractor agreement","podcasts","podnet","presidents","Professional Achievement Award","project management","provider webinars","publications","Regional and Urban Design Honor Award","renew membership","repositioning aia","rss","RUD award","rudat","scholarships","stalled projects","standard aia contract","subcontractor","sustainability","sustainable documents","Thomas Jefferson Award","Topaz","Topaz Medallion","transcripts","travel benefits","travel information","twenty-five year award","virtual convention","Whitney M. Young Jr. Award","yaf","young architects","Young Architects Award","Young Architects Award Eligibility","young architects forum"]
	

jQuery(document).ready(function() {
	// End Autosuggest init 	
	var a = jQuery('#mainSearchBox').autocomplete({
	autoSubmit: true,
	minChars:3,
	lookup: terms,
	maxHeight:300,
	width:215,
	zIndex: 9999,
	deferRequestBy: 0, //miliseconds
	noCache: false //default is false, set to true to disable caching
	});
	// End Autosuggest init 	

	
/***** Start Printing code *****/
	
	// Fixing logo print
	var prnDiv = 'div#headerLogo';
	jQuery(prnDiv).append('<div id="headerLogoPrint"><img src="http://code.aia.org/i/aia_logo_screen.png" /></div>');
	// end fix logo print
	
	// Replace print button with hidden popup
	var pDiv = 'div#pageToolsNav ul li#print';
	jQuery(pDiv).html('<a id="printCall" class="first" href="javascript:void(0);" title="Print" >Print</a> \
	<div id="prntParam"> \
		<span></span> \
		<div id="prntMSG"> \
			<input name="printads" type="checkbox" checked="checked" id="printads" value="yes" title="Print with Ads"> \
			<label for="printads">Print with Ads</label> \
			<input type="button" name="printBotton" id="printBotton" value="Print" title="Print"> \
		</div> \
	</div>');
	// End replace
	

	// Cookie init ****
	function setCookie(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}
	
	function getCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}
	
	function deleteCookie(name) {
		setCookie(name,"",-1);
	}
	// End Cookie  init ****

	// Check Cookie value ***
	cook = getCookie('aiaPrint');

	// add classes and ids in one variable and use function later for multiple options
	// make it shorter and easy to add more classes or ids.
	var ids = '.adContainer, #marketplace, #akr-ad-1, .ad220x183, #bottomAdRow'; // put all ads selleectors here
	
	// Show/hide
		if (cook == 'noAds'){
			jQuery(ids).addClass('prHide'); // reset ads
			jQuery('.levelThree').parent().addClass('L3full'); // Level3 full width
			if (typeof(jQuery.fn.prop) === 'function') {
				// jQuery.input.prop('disabled', 'test');
				jQuery("#printads").prop("checked", false);   // reset checkbox
			} else {
				jQuery("#printads").attr('checked', '')
			}
//			jQuery("#printads").prop("checked", false);   // reset checkbox
		
			
		} else {
			jQuery(ids).removeClass('prHide'); // reset ads
			jQuery('.levelThree').parent().removeClass('L3full'); // reset Level3
			if (typeof(jQuery.fn.prop) === 'function') {
				// jQuery.input.prop('disabled', 'test');
				jQuery("#printads").prop("checked", true);   // reset checkbox
			} else {
				jQuery("#printads").attr('checked', 'checked')
			}	
			
		
		} 
	
	
	
	// Printing after checking choices whin print button is clicked
	jQuery("#printBotton").click(function(event) {
		event.preventDefault();
		if (jQuery('#printads').is(':checked')){
			jQuery(ids).removeClass('prHide'); // Show ads
			jQuery('.levelThree').parent().removeClass('L3full'); // reset Level3
		// 	alert('Level3 fluid width removed!');
			setCookie('aiaPrint', 'yesAds', 1);	// Set Coockie
			
		//	jQuery('.levelThree').parent().addClass('grid_9'); // Make level3 page fluid width
		} else {
			jQuery(ids).addClass('prHide'); // Hide ads
			jQuery('.levelThree').parent().addClass('L3full'); // Level3 full width
			setCookie('aiaPrint', 'noAds', 1); // Set Coockie	
		//	jQuery('.levelThree').parent().removeClass('grid_9'); // Make level3 page fluid width
		}
		window.print();
	   });
	// End Check Cookie valu ***
	
	
	// Showing print choice when Print is clicked
	jQuery("#printCall").click(function(){ 
		// Show print popup choice
	//	alert('pop!');
		jQuery('#prntParam').slideToggle('fast');
		return false; 
	});
	
	// Handling click out side to hide choice window
	jQuery(document).click(function(event) { 
		if(jQuery(event.target).parents().index(jQuery('#prntParam')) == -1) {
			if(jQuery('#prntParam').is(":visible")) {
				jQuery('#prntParam').hide()
			}
		}        
	})

	// End click outside
	
});

